<template>
  <div class="search-form">
    <!-- 头部tab切换 -->
    <el-row type="flex" class="search-tab">
      <span
        v-for="(item, index) in tabs"
        :key="index"
        @click="handleSearchTab(item, index)"
        :class="{active: index === currentTab}"
      >
        <i :class="item.icon"></i>
        {{item.name}}
      </span>
    </el-row>

    <el-form class="search-form-content" ref="form" label-width="80px">
      <el-form-item label="出发城市">
        <!-- fetch-suggestions 返回输入建议的方法 -->
        <!-- select 点击选中建议项时触发 -->
        <el-autocomplete
          v-model="form.departCity"
          :fetch-suggestions="queryDepartSearch"
          :trigger-on-focus="false"
          :highlight-first-item="true"
          placeholder="请搜索出发城市"
          @select="handleDepartSelect"
          class="el-autocomplete"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="到达城市">
        <el-autocomplete
          v-model="form.destCity"
          :fetch-suggestions="queryDestSearch"
          :trigger-on-focus="false"
          :highlight-first-item="true"
          placeholder="请搜索到达城市"
          @select="handleDestSelect"
          class="el-autocomplete"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="出发时间">
        <!-- change 用户确认选择日期时触发 -->
        <el-date-picker
          v-model="form.departDate"
          type="date"
          placeholder="请选择日期"
          style="width: 100%;"
          @change="handleDate"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label>
        <el-button style="width:100%;" type="primary" icon="el-icon-search" @click="handleSubmit">搜索</el-button>
      </el-form-item>
      <div class="reverse">
        <span @click="handleReverse">换</span>
      </div>
    </el-form>
  </div>
</template>

<script>
import moment from "moment";
export default {
  data() {
    return {
      form: {
        departCity: "",
        departCode: "",
        destCity: "",
        destCode: "",
        departDate: ""
      },
      tabs: [
        { icon: "iconfont icondancheng", name: "单程" },
        { icon: "iconfont iconshuangxiang", name: "往返" }
      ],
      currentTab: 0,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      }
    };
  },
  methods: {
    // tab切换时触发
    handleSearchTab(item, index) {
      if (index == 1) {
        this.$confirm("目前暂不支持往返，请使用单程选票！", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning"
        });
      }
    },

    // 封装城市输入框从服务器获取数据
    getSuggestions(val) {
      return this.$axios({
        url: "/airs/city",
        params: {
          name: val
        }
      }).then(res => {
        const { data } = res.data;
        const suggestions = data.map(element => {
          return {
            value: element.name.replace(/市$/, ""),
            code: element.sort
          };
        });
        return suggestions.filter(ele => {
          return ele.code;
        });
      });
    },

    // 出发城市输入框获得焦点时触发
    // value 是选中的值，cb是回调函数，接收要展示的列表
    queryDepartSearch(value, cb) {
      this.getSuggestions(value).then(suggestions => {
        if (suggestions.length > 0) {
          // this.form.departCity = suggestions[0].value;
          // 假设真的到了最后发送前，没有设定城市代码
          // this.form.departCode = "";
          this.form.departCode = suggestions[0].code;
          cb(suggestions);
        } else {
          cb([
            {
              value: "不支持该城市"
            }
          ]);
        }
      });
    },

    // 目标城市输入框获得焦点时触发
    // value 是选中的值，cb是回调函数，接收要展示的列表
    queryDestSearch(value, cb) {
      this.getSuggestions(value).then(suggestions => {
        if (suggestions.length > 0) {
          // this.form.destCity = suggestions[0].value;
          // this.form.destCode = "";
          this.form.destCode = suggestions[0].code;
          cb(suggestions);
        } else {
          cb([
            {
              value: "不支持该城市"
            }
          ]);
        }
      });
    },

    // 出发城市下拉选择时触发
    handleDepartSelect(item) {
      this.form.departCode = item.code;
    },

    // 目标城市下拉选择时触发
    handleDestSelect(item) {
      this.form.destCode = item.code;
    },

    // 确认选择日期时触发
    handleDate(value) {
      this.form.departDate = moment(value).format("YYYY-MM-DD");
    },

    // 触发和目标城市切换时触发
    handleReverse() {
      const oldDepartCity = this.form.departCity;
      const oldDepartCode = this.form.departCode;
      this.form.departCity = this.form.destCity;
      this.form.departCode = this.form.destCode;
      this.form.destCity = oldDepartCity;
      this.form.destCode = oldDepartCode;
    },

    // 提交表单是触发
    async handleSubmit() {
      if (!this.form.departCode && this.form.departCity) {
        const suggestions = await this.getSuggestions(this.form.departCity);
        if (suggestions[0]) {
          this.form.departCode = suggestions[0].code;
        }
      }
      if (!this.form.destCode && this.form.destCity) {
        const suggestions = await this.getSuggestions(this.form.destCity);
        if (suggestions[0]) {
          this.form.destCode = suggestions[0].code;
        }
      }
      // 判断是否有为空
      if (!this.form.departCity) {
        this.$confirm("出发城市不能为空！", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning"
        });
        return;
      }
      if (!this.form.destCity) {
        this.$confirm("到达城市不能为空！", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning"
        });
        return;
      }
      if (!this.form.departDate) {
        this.$confirm("出发时间不能为空！", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning"
        });
        return;
      }
      // 判断出发城市和到达城市是否相同
      if (this.form.departCity === this.form.destCity) {
        this.$confirm("出发城市和到达城市不能相同！", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning"
        });
        return;
      }
      // console.log(this.form);
      this.form.departCity = this.form.departCity.replace(/市$/, "");
      this.form.destCity = this.form.destCity.replace(/市$/, "");

      // 跳转之前，应该将数据存放到store里面
      this.$store.commit("history/addHistory", this.form);
      this.$router.push({
        path: "/air/flights",
        query: this.form
      });
    }
  },
  mounted() {}
};
</script>

<style scoped lang="less">
.search-form {
  border: 1px #ddd solid;
  border-top: none;
  width: 360px;
  height: 350px;
  box-sizing: border-box;
}

.search-tab {
  span {
    display: block;
    flex: 1;
    text-align: center;
    height: 48px;
    line-height: 42px;
    box-sizing: border-box;
    border-top: 3px #eee solid;
    background: #eee;
  }

  .active {
    border-top-color: orange;
    background: #fff;
  }

  i {
    margin-right: 5px;
    font-size: 18px;

    &:first-child {
      font-size: 16px;
    }
  }
}

.search-form-content {
  padding: 15px 50px 15px 15px;
  position: relative;

  .el-autocomplete {
    width: 100%;
  }
}

.reverse {
  position: absolute;
  top: 35px;
  right: 15px;

  &:after,
  &:before {
    display: block;
    content: "";
    position: absolute;
    left: -35px;
    width: 25px;
    height: 1px;
    background: #ccc;
  }

  &:after {
    top: 0;
  }

  &:before {
    top: 60px;
  }

  span {
    display: block;
    position: absolute;
    top: 20px;
    right: 0;
    font-size: 12px;
    background: #999;
    color: #fff;
    width: 20px;
    height: 20px;
    line-height: 18px;
    text-align: center;
    border-radius: 2px;
    cursor: pointer;

    &:after,
    &:before {
      display: block;
      content: "";
      position: absolute;
      left: 10px;
      width: 1px;
      height: 20px;
      background: #ccc;
    }

    &:after {
      top: -20px;
    }

    &:before {
      top: 20px;
    }
  }
}
</style>
